package cn.portx.el;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf3.dorado.jpa.JpaUtil;
import com.bstek.bdf3.security.orm.RoleGrantedAuthority;

import cn.portx.entity.ExpenseAuthority;

@Component
public class LoadExpenseAuthority {

	@Transactional(readOnly = true)
	public String load() throws IOException {
		Map<String, String> map = new HashMap<String, String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String put(String key, String value) {
				if (this.containsKey(key)) {
					String oldValue = this.get(key);
					if (!StringUtils.equals(value, oldValue)) {
						return super.put(key, value.compareTo(oldValue) < 0 ? oldValue : value);
					} else {
						return value;
					}
				}
				return super.put(key, value);
			}
		};
		Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (object instanceof UserDetails) {
			UserDetails user = (UserDetails) object;
			List<ExpenseAuthority> list = JpaUtil.linq(ExpenseAuthority.class).exists(RoleGrantedAuthority.class)
					.equalProperty("roleId", "roleId").equal("actorId", user.getUsername()).end().list();
			for (ExpenseAuthority ea : list) {
				map.put(ea.getExpenseItemId(), ea.getAuthority());
			}
		}
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(map);
		return json;
	}

}
